<template>
    <div id="wrapper">
        <el-card class="box-card">
            <el-select
                v-model="filterMainProject"
                placeholder="筛选主项目"
                clearable
                @change="changeFilterMainProject"
            >
                <el-option
                    v-for="item in projectData"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                >
                </el-option>
            </el-select>
            <el-table
                class="marT"
                size="mini"
                :data="tableData"
                :border="true"
                :header-cell-style="{ background: '#eef1f6' }"
                style="width: 100%; margin-bottom: 15px"
            >
                <el-table-column
                    width="200px"
                    align="center"
                    property="business_group"
                    label="事业群"
                ></el-table-column>
                <el-table-column align="center" width="200px" label="项目名称">
                    <template slot-scope="scope">
                        {{ scope.row.project_name }}
                        <el-tag
                            size="mini"
                            type="success"
                            v-if="scope.row.version"
                            >v{{ scope.row.version }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column
                    align="center"
                    property="project_manager"
                    label="项目经理"
                ></el-table-column>
                <el-table-column
                    width="150px"
                    align="center"
                    property="form_status"
                    label="状态"
                ></el-table-column>
                <el-table-column
                    align="center"
                    property="created_at"
                    label="立项日期"
                ></el-table-column>
                <el-table-column
                    align="center"
                    property="changed_at"
                    label="变更日期"
                ></el-table-column>
                <el-table-column
                    align="center"
                    property="submitter"
                    label="创建人"
                    width="150px"
                >
                    <template slot-scope="scope">
                        {{ scope.row.creator_name }}
                        {{ scope.row.creator_ldap }}
                    </template>
                </el-table-column>
                <el-table-column width="290px">
                    <template slot-scope="scope">
                        <el-button-group>
                            <el-button
                                type="primary"
                                size="mini"
                                @click="viewProject(scope.row.form_id)"
                            >
                                查看
                            </el-button>
                            <el-button
                                type="primary"
                                size="mini"
                                @click="editProject(scope.row.form_id)"
                                :disabled="!scope.row.can_edit"
                            >
                                编辑
                            </el-button>
                            <el-button
                                type="primary"
                                size="mini"
                                @click="deletProject(scope.row.id)"
                                :disabled="!scope.row.can_edit || scope.row.can_change"
                            >
                                删除
                            </el-button>
                            <el-dropdown
                                trigger="click"
                                size="medium"
                                type="primary"
                            >
                                <el-button type="primary" size="mini">
                                    历史版本<i
                                        class="el-icon-arrow-down el-icon--right"
                                    ></i>
                                </el-button>
                                <el-dropdown-menu slot="dropdown">
                                    <el-dropdown-item
                                        v-bind:key="index"
                                        v-for="(history, index) in scope.row
                                            .history"
                                    >
                                        <router-link
                                            :to="{
                                                name: 'view',
                                                params: {
                                                    id: history.form_id
                                                }
                                            }"
                                            >v{{ history.version }}</router-link
                                        >
                                    </el-dropdown-item>
                                    <el-dropdown-item
                                        disabled
                                        v-if="!scope.row.history.length"
                                        >无历史版本
                                    </el-dropdown-item>
                                </el-dropdown-menu>
                            </el-dropdown>
                        </el-button-group>
                        <!-- <el-button
                            type="text"
                            size="mini"
                            :disabled="!scope.row.workflow_link"
                            @click="viewWorkflowRequest(scope.row.workflow_link)"
                        >
                            OA流程
                        </el-button> -->
                        <span v-if="scope.row.status == '!待提交'"
                            >|
                            <el-popconfirm
                                title="确定删除吗？"
                                @onConfirm="delProject(scope.row.project_name)"
                            >
                                <el-button
                                    slot="reference"
                                    type="text"
                                    size="mini"
                                >
                                    删除
                                </el-button>
                            </el-popconfirm>
                        </span>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                v-show="tableTotal > 10"
                background
                layout="prev, pager, next"
                :page-size="tableSize"
                @size-change="tableSizeChange"
                @current-change="tableCurrentChange"
                :current-page="tableCurrent"
                style="text-align: center"
                :total="tableTotal"
            >
            </el-pagination>
        </el-card>
        <el-dialog
            title="项目查看"
            :visible.sync="dialogVisible"
            width="90%"
            :destroy-on-close="true"
        >
            <projectform
                v-if="dialogVisible"
                :form="itemFormData"
                :calculated="calculated"
                ref="dialogform"
            ></projectform>
            <span slot="footer" class="dialog-footer">
                <!--         <el-button @click="()=>dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button> -->
            </span>
        </el-dialog>
        <el-dialog
            title="项目编辑"
            :visible.sync="dialogEditVisible"
            width="90%"
            @close="editProjectOver"
            :destroy-on-close="true"
        >
            <projectform
                v-if="dialogEditVisible"
                :form="itemFormData"
                :calculated="calculated"
                canEdit="true"
            ></projectform>
            <span slot="footer" class="dialog-footer">
                <!-- <el-button @click="editProjectOver">取 消</el-button>
        <el-button type="primary" @click="editProjectOver">确 定</el-button> -->
            </span>
        </el-dialog>
    </div>
</template>
<script>
import { getHeader } from '@/app.config';
import { getName } from '@/utils/auth';
import http from '@/views/sys/axios';
import { mapState, mapMutations } from 'vuex';
import projectForm from './components/projectForm.vue';
export default {
    components: {
        projectform: projectForm
    },
    data() {
        return {
            BACKEND_API: process.env.VUE_APP_PROJECT_REQUEST_HOST,
            ldap: getName(),
            dialogVisible: false,
            dialogEditVisible: false,
            tableData: [],
            tableSize: 10,
            tableCurrent: 1,
            tableTotal: 15,
            itemFormData: {},
            calculated: {},
            filterMainProject: '',
            projectData: []
        };
    },
    filters: {
        numFilter(value) {
            let tempVal = parseFloat(value || 0).toFixed(3);
            let realVal = tempVal.substring(0, tempVal.length - 1);
            return realVal;
        },
        num45Filter(value) {
            // 四舍五入
            let tempVal = Math.pow(10, 2);
            return Math.round(value * tempVal) / tempVal;
        }
    },
    created() {
        this.getData();
        this.getUserInfo().then(res => {
            this.fetchProject(res.data.data[0].id);
        });
    },
    mounted() {
        this.$nextTick(() => {});
    },
    methods: {
        deletProject(id) {
            this.$confirm(`是否删除项目`, '提示', {
                confirmButtonText: '是',
                cancelButtonText: '否',
                type: 'warning'
            })
            .then(() => {
                this.$axios.get(
                    `${this.BACKEND_API}/api/base/project/delete?id=${id}`
                ).then(res=>{
                    this.getProjectList()
                    this.$message({
                        message: res.data.msg_zh,
                        type: 'success'
                    });
                })
            }).catch(() => {
                console.log("取消删除")
            });
        },
        getData() {
            this.getProjectList();
        },
        getProjectList() {
            this.$axios({
                url: `${this.BACKEND_API}/api/base/project`,
                method: 'get',
                params: {
                    page: this.tableCurrent,
                    per_page: this.tableSize,
                    ldap: this.ldap,
                    main: this.filterMainProject
                }
            }).then(res => {
                this.tableData = res.data.data;
                this.tableTotal = res.data.total;
                this.tableData.forEach((item,index)=>{
                
                    this.$axios.get(
                        `${this.BACKEND_API}/api/base/project/joint_edit?workflow_id=${item.id}&ldap=${this.ldap}`
                    ).then(res=>{
                        if(res.data.status === false && item.creator_ldap !== this.ldap){
                            this.tableData[index].can_edit = false;
                        } else if(item.creator_ldap !== this.ldap){
                            this.tableData[index].can_change = true;
                        }
                    }) 
                })
            });
        },
        getFormDataByProjectNameEdit(project_name) {
            this.$axios({
                url:
                    this.BACKEND_API +
                    '/api/base/project/apply?project_name=' +
                    project_name,
                method: 'get'
            }).then(res => {
                this.itemFormData = res.data.data.form;
                this.calculated = res.data.data.calculated;
            });
        },
        getFormDataByProjectNameDetails(project_name) {
            this.$axios({
                url:
                    this.BACKEND_API +
                    '/api/base/project/apply?project_name=' +
                    project_name,
                method: 'get'
            }).then(res => {
                this.itemFormData = res.data.data.form;
                this.calculated = res.data.data.calculated;
                this.dialogVisible = true;
            });
        },
        viewProject(id) {
            console.log(`redirect to ${id}`);
            this.$router.push({ name: 'view', params: { id: id } });
        },
        editProject(id) {
            this.$router.push({ name: 'edit', params: { id: id } });
        },
        changeProject(id) {
            this.$message.info('正在创建');
            this.$axios({
                url: `${this.BACKEND_API}/api/base/workflow/change`,
                method: 'post',
                data: {
                    form_id: id
                }
            }).then(res => {
                this.$router.push({
                    name: 'change',
                    params: { id: res.data.data }
                });
            });
        },
        delProject(project_name) {
            this.$axios({
                url: this.BACKEND_API + '/api/base/project',
                method: 'post',
                data: {
                    project_name: project_name
                }
            }).then(res => {
                console.log(res);
                this.$message.info(`${project_name} 删除中..`);
            });
        },
        editProjectOver() {
            this.dialogEditVisible = false;
            this.getProjectList();
        },
        tableCurrentChange(val) {
            this.tableCurrent = val;
            this.getData();
        },
        tableSizeChange(val) {
            this.tableSize = val;
            this.getData();
        },
        viewWorkflowRequest(url) {
            window.open(url, '_blank');
        },
        getUserInfo() {
            return new Promise((resolve, reject) => {
                this.$axios
                    .get(
                        `${
                            process.env.VUE_APP_PROJECT_REQUEST_HOST
                        }/api/base/employee/`,
                        {
                            params: {
                                ldap: getName()
                            }
                        }
                    )
                    .then(response => {
                        this.userInfo = response.data.data[0];
                        resolve(response);
                    })
                    .catch(err => {
                        reject(err);
                    });
            });
        },
        fetchProject(userId) {
            this.$axios
                .get(
                    `${
                        process.env.VUE_APP_PROJECT_REQUEST_HOST
                    }/api/base/parent_project/`,
                    {
                        params: {
                            create_by: userId,
                            ordering: '-create_date'
                        }
                    }
                )
                .then(response => {
                    this.projectData = response.data;
                });
        },
        changeFilterMainProject() {
            this.getProjectList();
        }
    }
};
</script>
<style lang="scss" scoped>
@import '../../assets/common/common.scss';
/deep/ .el-table th.gutter {
    display: table-cell !important;
}
/deep/ .el-dialog {
    background-color: #eeeeee;
}
/deep/ .el-divider__text {
    color: #ffffff;
    font-size: 20px;
    font-weight: 600;
    background-color: #e6a23c;
    padding: 6px 16px;
}
/deep/ .el-divider--horizontal {
    margin: 40px 0;
    height: 2px;
}
#wrapper {
    padding: 32px;
    background-color: rgb(240, 242, 245);
    position: relative;
}
.box {
    display: flex;
    div {
        margin: auto;
    }
}
.fade-enter-active,
.fade-leave-active {
    transition: opacity 0.5s;
}
.fade-enter,
.fade-leave-to {
    opacity: 0;
}
.toTop {
    position: fixed;
    bottom: 80px;
    right: 25px;
    z-index: 10;
}
.details {
    color: #1890ff;
    text-decoration: underline;
    cursor: pointer;
}
.choose {
    padding: 20px 0;
    .flex-box {
        display: flex;
        flex-wrap: nowrap;
        .flexEl {
            flex: 1;
            margin: auto;
        }
        .text-align {
            text-align: center;
        }
        .el {
            flex: 0 0 90%;
        }
    }
    .time {
        position: absolute;
        top: 20px;
        right: 41%;
        font-size: 14px;
        color: #606266;
    }
    .newReport {
        position: absolute;
        top: 20px;
        right: 20px;
    }
}
.border {
    box-sizing: content-box;
    height: 0;
    overflow: visible;
    margin-top: 1rem;
    margin-bottom: 1rem;
    border: 0;
    border-top: 1px solid rgba(0, 0, 0, 0.1);
}
.primary {
    color: #409eff;
    font-size: 30px;
    margin-top: 20px;
    margin-bottom: 10px;
    font-weight: 400;
}
.bgColor {
    background: #fff;
}
.pad {
    padding: 0 20px;
    padding-top: 20px;
}
.marT {
    margin-top: 20px;
}
.btn-group {
    text-align: right;
}
.mar {
    margin: 0 20px;
    margin-top: 20px;
}
.table {
    padding-bottom: 10px;
}
.text {
    font-size: 14px;
}
.item {
    margin-bottom: 18px;
}
.clearfix:before,
.clearfix:after {
    display: table;
    content: '';
}
.clearfix:after {
    clear: both;
}
</style>
